<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"littlefxc.github.io","root":"/","images":"/images","scheme":"Mist","version":"8.2.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>
<meta name="description" content="Spring + MyBatis + MySQL主从分离基于 Docker 的 MySQL 主从复制搭建基于 Docker 的 MySQL 主从复制搭建 前言在大型应用程序中，配置主从数据库并使用读写分离是常见的设计模式。而要对现有的代码在不多改变源码的情况下，可以使用 Spring 的 AbstractRoutingDataSource 和 Mybatis 的 Interceptor 为核心做到">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring+MyBatis+MySQL主从分离">
<meta property="og:url" content="http://littlefxc.github.io/2019/05/07/Spring-MyBatis-MySQL%E4%B8%BB%E4%BB%8E%E5%88%86%E7%A6%BB/index.html">
<meta property="og:site_name" content="一年春又来">
<meta property="og:description" content="Spring + MyBatis + MySQL主从分离基于 Docker 的 MySQL 主从复制搭建基于 Docker 的 MySQL 主从复制搭建 前言在大型应用程序中，配置主从数据库并使用读写分离是常见的设计模式。而要对现有的代码在不多改变源码的情况下，可以使用 Spring 的 AbstractRoutingDataSource 和 Mybatis 的 Interceptor 为核心做到">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20190426091910423.png">
<meta property="article:published_time" content="2019-05-07T12:30:26.000Z">
<meta property="article:modified_time" content="2021-03-25T13:15:49.009Z">
<meta property="article:author" content="一年春又来">
<meta property="article:tag" content="mysql">
<meta property="article:tag" content="mybatis">
<meta property="article:tag" content="spring">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20190426091910423.png">


<link rel="canonical" href="http://littlefxc.github.io/2019/05/07/Spring-MyBatis-MySQL%E4%B8%BB%E4%BB%8E%E5%88%86%E7%A6%BB/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>
<title>Spring+MyBatis+MySQL主从分离 | 一年春又来</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="一年春又来" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">一年春又来</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="home                          //首页 fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="archive          //归档 fa-fw"></i>归档</a></li>
        <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="th           //分类 fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="tags                     //标签 fa-fw"></i>标签</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Spring-MyBatis-MySQL%E4%B8%BB%E4%BB%8E%E5%88%86%E7%A6%BB"><span class="nav-text">Spring + MyBatis + MySQL主从分离</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9F%BA%E4%BA%8E-Docker-%E7%9A%84-MySQL-%E4%B8%BB%E4%BB%8E%E5%A4%8D%E5%88%B6%E6%90%AD%E5%BB%BA"><span class="nav-text">基于 Docker 的 MySQL 主从复制搭建</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%89%8D%E8%A8%80"><span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%85%8D%E7%BD%AE%E5%A4%9A%E6%95%B0%E6%8D%AE%E6%BA%90"><span class="nav-text">配置多数据源</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8-Spring-%E7%9A%84-AbstractRoutingDataSource-%E5%8A%A8%E6%80%81%E5%88%87%E6%8D%A2%E6%95%B0%E6%8D%AE%E6%BA%90"><span class="nav-text">使用 Spring 的 AbstractRoutingDataSource 动态切换数据源</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%94%A8%E6%9E%9A%E4%B8%BE%E6%A0%87%E8%AE%B0%E8%AF%BB%E5%86%99%E6%95%B0%E6%8D%AE%E6%BA%90"><span class="nav-text">用枚举标记读写数据源</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%94%A8-ThreadLocal-%E8%AE%B0%E5%BD%95%E5%BD%93%E5%89%8D%E7%BA%BF%E7%A8%8B%E6%95%B0%E6%8D%AE%E6%BA%90"><span class="nav-text">用 ThreadLocal 记录当前线程数据源</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E8%B7%AF%E7%94%B1%E6%95%B0%E6%8D%AE%E6%BA%90%E5%AE%9E%E7%8E%B0"><span class="nav-text">自定义路由数据源实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%85%8D%E7%BD%AE%E8%B7%AF%E7%94%B1%E6%95%B0%E6%8D%AE%E6%BA%90"><span class="nav-text">配置路由数据源</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8-MyBatis-%E7%9A%84-Interceptor-%E6%8B%A6%E6%88%AA%E5%99%A8%E5%AF%B9update%E4%BD%BF%E7%94%A8%E5%86%99%E5%BA%93%EF%BC%8C%E5%AF%B9query%E4%BD%BF%E7%94%A8%E8%AF%BB%E5%BA%93"><span class="nav-text">使用 MyBatis 的 Interceptor 拦截器对update使用写库，对query使用读库</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%B5%8B%E8%AF%95"><span class="nav-text">测试</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">一年春又来</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">234</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">38</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">125</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2019/05/07/Spring-MyBatis-MySQL%E4%B8%BB%E4%BB%8E%E5%88%86%E7%A6%BB/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Spring+MyBatis+MySQL主从分离
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2019-05-07 20:30:26" itemprop="dateCreated datePublished" datetime="2019-05-07T20:30:26+08:00">2019-05-07</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-03-25 21:15:49" itemprop="dateModified" datetime="2021-03-25T21:15:49+08:00">2021-03-25</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Java/" itemprop="url" rel="index"><span itemprop="name">Java</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="Spring-MyBatis-MySQL主从分离"><a href="#Spring-MyBatis-MySQL主从分离" class="headerlink" title="Spring + MyBatis + MySQL主从分离"></a>Spring + MyBatis + MySQL主从分离</h1><h2 id="基于-Docker-的-MySQL-主从复制搭建"><a href="#基于-Docker-的-MySQL-主从复制搭建" class="headerlink" title="基于 Docker 的 MySQL 主从复制搭建"></a>基于 Docker 的 MySQL 主从复制搭建</h2><p><a target="_blank" rel="noopener" href="https://blog.csdn.net/Little_fxc/article/details/89477284">基于 Docker 的 MySQL 主从复制搭建</a></p>
<h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>在大型应用程序中，配置主从数据库并使用读写分离是常见的设计模式。而要对现有的代码在不多改变源码的情况下，<br>可以使用 Spring 的 <code>AbstractRoutingDataSource</code> 和 Mybatis 的 <code>Interceptor</code> 为核心做到感知mysql读写分离</p>
<span id="more"></span>

<h2 id="配置多数据源"><a href="#配置多数据源" class="headerlink" title="配置多数据源"></a>配置多数据源</h2><p>使用了 druid 数据库连接池，配置 master datasource 为写数据库，配置 slave datasource 为读数据库。</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">spring.datasource.druid.filter.slf4j.enabled=true</span></span><br><span class="line"><span class="string">spring.datasource.druid.filter.slf4j.statement-create-after-log-enabled=false</span></span><br><span class="line"><span class="string">spring.datasource.druid.filter.slf4j.statement-close-after-log-enabled=false</span></span><br><span class="line"><span class="string">spring.datasource.druid.filter.slf4j.result-set-open-after-log-enabled=false</span></span><br><span class="line"><span class="string">spring.datasource.druid.filter.slf4j.result-set-close-after-log-enabled=false</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># master datasource</span></span><br><span class="line"><span class="string">spring.datasource.druid.master.driver-class-name=com.mysql.cj.jdbc.Driver</span></span><br><span class="line"><span class="string">spring.datasource.druid.master.url=jdbc:mysql://localhost:3306/learn?useSSl=false</span></span><br><span class="line"><span class="string">spring.datasource.druid.master.password=root</span></span><br><span class="line"><span class="string">spring.datasource.druid.master.username=root</span></span><br><span class="line"><span class="comment"># slave datasource</span></span><br><span class="line"><span class="string">spring.datasource.druid.slave.driver-class-name=com.mysql.cj.jdbc.Driver</span></span><br><span class="line"><span class="string">spring.datasource.druid.slave.url=jdbc:mysql://localhost:3307/learn?useSSl=false</span></span><br><span class="line"><span class="string">spring.datasource.druid.slave.password=root</span></span><br><span class="line"><span class="string">spring.datasource.druid.slave.username=root</span></span><br><span class="line"></span><br><span class="line"><span class="string">spring.jackson.date-format=yyyy-MM-dd</span> <span class="string">HH:mm:ss</span></span><br><span class="line"><span class="string">spring.jackson.time-zone=GMT+8</span></span><br><span class="line"><span class="string">spring.jackson.default-property-inclusion=always</span></span><br><span class="line"><span class="string">spring.jackson.property-naming-strategy=SNAKE_CASE</span></span><br><span class="line"></span><br><span class="line"><span class="string">mybatis.type-aliases-package=com.fengxuechao.examples.rwdb.entity</span></span><br><span class="line"><span class="string">mybatis.configuration.use-generated-keys=true</span></span><br><span class="line"><span class="string">mybatis.configuration.map-underscore-to-camel-case=true</span></span><br><span class="line"><span class="string">mybatis.configuration.default-fetch-size=100</span></span><br><span class="line"><span class="string">mybatis.configuration.default-statement-timeout=30</span></span><br><span class="line"><span class="string">mybatis.configuration.cache-enabled=true</span></span><br><span class="line"></span><br><span class="line"><span class="string">logging.level.root=info</span></span><br><span class="line"><span class="string">logging.level.com.fengxuechao.examples.rwdb=debug</span></span><br><span class="line"><span class="string">logging.level.druid.sql.Statement=error</span></span><br></pre></td></tr></table></figure>

<h2 id="使用-Spring-的-AbstractRoutingDataSource-动态切换数据源"><a href="#使用-Spring-的-AbstractRoutingDataSource-动态切换数据源" class="headerlink" title="使用 Spring 的 AbstractRoutingDataSource 动态切换数据源"></a>使用 Spring 的 AbstractRoutingDataSource 动态切换数据源</h2><h3 id="用枚举标记读写数据源"><a href="#用枚举标记读写数据源" class="headerlink" title="用枚举标记读写数据源"></a>用枚举标记读写数据源</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">enum</span> <span class="title">RoutingType</span> </span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 代表写数据库</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    MASTER,</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 代表读数据库</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    SLAVE;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="用-ThreadLocal-记录当前线程数据源"><a href="#用-ThreadLocal-记录当前线程数据源" class="headerlink" title="用 ThreadLocal 记录当前线程数据源"></a>用 ThreadLocal 记录当前线程数据源</h3><p>在Servlet的线程模型中，使用ThreadLocal存储key最合适，因此，编写一个RoutingDataSourceContext，来设置并动态存储key：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RoutingDataSourceContext</span> <span class="keyword">implements</span> <span class="title">AutoCloseable</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> ThreadLocal&lt;RoutingType&gt; contextHolder = <span class="keyword">new</span> ThreadLocal&lt;&gt;();</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">RoutingDataSourceContext</span><span class="params">(RoutingType routingType)</span> </span>&#123;</span><br><span class="line">      contextHolder.set(routingType);</span><br><span class="line">   &#125;</span><br><span class="line">	</span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">setRoutingType</span><span class="params">(RoutingType routingType)</span> </span>&#123;</span><br><span class="line">      Assert.notNull(routingType, <span class="string">&quot;routingType cannot be null&quot;</span>);</span><br><span class="line">      contextHolder.set(routingType);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> RoutingType <span class="title">getRoutingType</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> contextHolder.get();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">clear</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      contextHolder.remove();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">close</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">      clear();</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="自定义路由数据源实现"><a href="#自定义路由数据源实现" class="headerlink" title="自定义路由数据源实现"></a>自定义路由数据源实现</h3><p>用Spring内置的RoutingDataSource，把两个真实的数据源代理为一个动态数据源：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RoutingDataSource</span> <span class="keyword">extends</span> <span class="title">AbstractRoutingDataSource</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> Object <span class="title">determineCurrentLookupKey</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> RoutingDataSourceContext.getRoutingType();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="配置路由数据源"><a href="#配置路由数据源" class="headerlink" title="配置路由数据源"></a>配置路由数据源</h3><p>对于 <code>RoutingDataSource</code> 需要在SpringBoot中配置好并设置为主数据源：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> fengxuechao</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@EnableTransactionManagement</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DbConfig</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 写数据库</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="meta">@ConfigurationProperties(&quot;spring.datasource.druid.master&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> DataSource <span class="title">masterDataSource</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> DruidDataSourceBuilder.create().build();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 读数据库</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="meta">@ConfigurationProperties(&quot;spring.datasource.druid.slave&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> DataSource <span class="title">slaveDataSource</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> DruidDataSourceBuilder.create().build();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 路由数据源</span></span><br><span class="line"><span class="comment">     * 一定要加 <span class="doctag">@Primary</span> 使得 &#123;<span class="doctag">@link</span> MybatisInterceptor&#125; 插件生效</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="meta">@Primary</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> DataSource <span class="title">dataSource</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        log.info(<span class="string">&quot;create routing datasource...&quot;</span>);</span><br><span class="line">        Map&lt;Object, Object&gt; map = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">        map.put(RoutingType.MASTER, masterDataSource());</span><br><span class="line">        map.put(RoutingType.SLAVE, slaveDataSource());</span><br><span class="line">        RoutingDataSource routing = <span class="keyword">new</span> RoutingDataSource();</span><br><span class="line">        routing.setTargetDataSources(map);</span><br><span class="line">        routing.setDefaultTargetDataSource(masterDataSource());</span><br><span class="line">        <span class="keyword">return</span> routing;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 添加 MybatisInterceptor 拦截器</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> dataSource</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> SqlSessionFactoryBean <span class="title">sqlSessionFactory</span><span class="params">(DataSource dataSource)</span> </span>&#123;</span><br><span class="line">        SqlSessionFactoryBean sfb = <span class="keyword">new</span> SqlSessionFactoryBean();</span><br><span class="line">        sfb.setDataSource(dataSource);</span><br><span class="line">        sfb.setPlugins(<span class="keyword">new</span> Interceptor[]&#123;<span class="keyword">new</span> MybatisInterceptor()&#125;);</span><br><span class="line">        <span class="keyword">return</span> sfb;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="使用-MyBatis-的-Interceptor-拦截器对update使用写库，对query使用读库"><a href="#使用-MyBatis-的-Interceptor-拦截器对update使用写库，对query使用读库" class="headerlink" title="使用 MyBatis 的 Interceptor 拦截器对update使用写库，对query使用读库"></a>使用 MyBatis 的 Interceptor 拦截器对update使用写库，对query使用读库</h2><p>原理：</p>
<p>查看 <code>org.apache.ibatis.executor.Executor</code> 可以发现 MyBatis 执行 sql 的语句都在这里边了：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Executor</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 执行sql 的 update, delete, insert</span></span><br><span class="line">  <span class="function"><span class="keyword">int</span> <span class="title">update</span><span class="params">(MappedStatement ms, Object parameter)</span> <span class="keyword">throws</span> SQLException</span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 执行sql 的 select</span></span><br><span class="line">  &lt;E&gt; <span class="function">List&lt;E&gt; <span class="title">query</span><span class="params">(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey cacheKey, BoundSql boundSql)</span> <span class="keyword">throws</span> SQLException</span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 执行sql 的 select</span></span><br><span class="line">  &lt;E&gt; <span class="function">List&lt;E&gt; <span class="title">query</span><span class="params">(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler)</span> <span class="keyword">throws</span> SQLException</span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>只要拦截这三个方法，是的 update() 方法使用写数据库，query() 方法使用读数据库就可以做到在不改写原业务代码的情况下使用多数据源，同时让Spring事务也正常运行。 </p>
<p>拦截器：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 拦截器，对update使用写库，对query使用读库</span></span><br><span class="line"><span class="comment"> * 优势：源代码不变（通过mybatis拦截器），易扩展</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> fengxuechao</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2019-03-22</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Intercepts(&#123;</span></span><br><span class="line"><span class="meta">        @Signature(</span></span><br><span class="line"><span class="meta">                type = Executor.class,</span></span><br><span class="line"><span class="meta">                method = &quot;update&quot;,</span></span><br><span class="line"><span class="meta">                args = &#123;MappedStatement.class, Object.class&#125;),</span></span><br><span class="line"><span class="meta">        @Signature(</span></span><br><span class="line"><span class="meta">                type = Executor.class,</span></span><br><span class="line"><span class="meta">                method = &quot;query&quot;,</span></span><br><span class="line"><span class="meta">                args = &#123;MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class&#125;),</span></span><br><span class="line"><span class="meta">&#125;)</span></span><br><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MybatisInterceptor</span> <span class="keyword">implements</span> <span class="title">Interceptor</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 用map对象缓存数据，数据量大的话，此处需要优化。</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Map&lt;String, RoutingType&gt; cacheMap = <span class="keyword">new</span> ConcurrentHashMap&lt;&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 通过正则表达式，拦截sql语句匹配类型设置数据源。</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String REGEX = <span class="string">&quot;.*insert\\u0020.*|.*delete\\u0020.*|.*update\\u0020.*&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">intercept</span><span class="params">(Invocation invocation)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        <span class="keyword">boolean</span> synchronizationActive = TransactionSynchronizationManager.isSynchronizationActive();</span><br><span class="line">        <span class="keyword">if</span> (!synchronizationActive) &#123;</span><br><span class="line">            Object[] objects = invocation.getArgs();</span><br><span class="line">            MappedStatement ms = (MappedStatement) objects[<span class="number">0</span>];</span><br><span class="line"></span><br><span class="line">            RoutingType routingType;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> ((routingType = cacheMap.get(ms.getId())) == <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="comment">//读方法</span></span><br><span class="line">                <span class="keyword">if</span> (ms.getSqlCommandType().equals(SqlCommandType.SELECT)) &#123;</span><br><span class="line">                    <span class="comment">//!selectKey 为自增id查询主键(SELECT LAST_INSERT_ID() )方法，使用主库</span></span><br><span class="line">                    <span class="keyword">if</span> (ms.getId().contains(SelectKeyGenerator.SELECT_KEY_SUFFIX)) &#123;</span><br><span class="line">                        routingType = RoutingType.MASTER;</span><br><span class="line">                    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                        BoundSql boundSql = ms.getSqlSource().getBoundSql(objects[<span class="number">1</span>]);</span><br><span class="line">                        String sql = boundSql.getSql().toLowerCase(Locale.CHINA).replaceAll(<span class="string">&quot;[\\t\\n\\r]&quot;</span>, <span class="string">&quot; &quot;</span>);</span><br><span class="line">                        <span class="keyword">if</span> (sql.matches(REGEX)) &#123;</span><br><span class="line">                            routingType = RoutingType.MASTER;</span><br><span class="line">                        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                            routingType = RoutingType.SLAVE;</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    routingType = RoutingType.MASTER;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">if</span> (log.isDebugEnabled())&#123;</span><br><span class="line">                    log.debug(<span class="string">&quot;设置方法[&#123;&#125;] use [&#123;&#125;] Strategy, SqlCommandType [&#123;&#125;]..&quot;</span>, ms.getId(), routingType.name(), ms.getSqlCommandType().name());</span><br><span class="line">                &#125;</span><br><span class="line">                cacheMap.put(ms.getId(), routingType);</span><br><span class="line">            &#125;</span><br><span class="line">            RoutingDataSourceContext.setRoutingType(routingType);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> invocation.proceed();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">plugin</span><span class="params">(Object target)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (target <span class="keyword">instanceof</span> Executor) &#123;</span><br><span class="line">            <span class="keyword">return</span> Plugin.wrap(target, <span class="keyword">this</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> target;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setProperties</span><span class="params">(Properties properties)</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>注意：需要在 Mybatis 的 SqlSessionFactory 中将此拦截器放入</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 添加 MybatisInterceptor 拦截器</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> dataSource</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> SqlSessionFactoryBean <span class="title">sqlSessionFactory</span><span class="params">(DataSource dataSource)</span> </span>&#123;</span><br><span class="line">    SqlSessionFactoryBean sfb = <span class="keyword">new</span> SqlSessionFactoryBean();</span><br><span class="line">    sfb.setDataSource(dataSource);</span><br><span class="line">    sfb.setPlugins(<span class="keyword">new</span> Interceptor[]&#123;<span class="keyword">new</span> MybatisInterceptor()&#125;);</span><br><span class="line">    <span class="keyword">return</span> sfb;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="测试"><a href="#测试" class="headerlink" title="测试"></a>测试</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> fengxuechao</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Repository</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">CityMapper</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Select(&quot;SELECT id,name,city_code as cityCode,post_code as postCode FROM city WHERE id = #&#123;id&#125; limit 1&quot;)</span></span><br><span class="line">    <span class="function">City <span class="title">findById</span><span class="params">(Integer id)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Insert(&quot;INSERT INTO city(name, city_code, post_code) VALUES(#&#123;name&#125;, #&#123;cityCode&#125;, #&#123;postCode&#125;)&quot;)</span></span><br><span class="line">    <span class="meta">@Options(useGeneratedKeys = true, keyProperty = &quot;id&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">insert</span><span class="params">(City city)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Select(&quot;SELECT * FROM city WHERE id = #&#123;id&#125; limit 100&quot;)</span></span><br><span class="line">    <span class="function">List&lt;City&gt; <span class="title">findAll</span><span class="params">()</span></span>;</span><br><span class="line">    </span><br><span class="line">	<span class="meta">@Update(&quot;UPDATE city SET name=#&#123;name&#125;,city_code=#&#123;cityCode&#125;,post_code=#&#123;postCode&#125; WHERE id =#&#123;id&#125;&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">update</span><span class="params">(City city)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> fengxuechao</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2019/3/22</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="meta">@RequestMapping(&quot;/city&quot;)</span></span><br><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CityController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    CityMapper cityMapper;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//    @RoutingWith(value = RoutingType.SLAVE)</span></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/&#123;id&#125;&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> City <span class="title">get</span><span class="params">(<span class="meta">@PathVariable</span> Integer id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> cityMapper.findById(id);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;City&gt; <span class="title">list</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> cityMapper.findAll();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@PutMapping</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> City <span class="title">update</span><span class="params">(<span class="meta">@RequestBody</span> City city)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (city.getId() != <span class="keyword">null</span>) &#123;</span><br><span class="line">            cityMapper.update(city);</span><br><span class="line">            cityMapper.findById(city.getId());</span><br><span class="line">            <span class="keyword">return</span> city;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>日志：</p>
<p><img src="https://img-blog.csdnimg.cn/20190426091910423.png" alt="在这里插入图片描述"></p>
<p>参考：</p>
<p><a target="_blank" rel="noopener" href="https://www.liaoxuefeng.com/article/00151054582348974482c20f7d8431ead5bc32b30354705000">https://www.liaoxuefeng.com/article/00151054582348974482c20f7d8431ead5bc32b30354705000</a></p>
<p><a target="_blank" rel="noopener" href="https://www.cnblogs.com/fangjian0423/p/mybatis-interceptor.html">https://www.cnblogs.com/fangjian0423/p/mybatis-interceptor.html</a></p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/mysql/" rel="tag"># mysql</a>
              <a href="/tags/mybatis/" rel="tag"># mybatis</a>
              <a href="/tags/spring/" rel="tag"># spring</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2019/05/07/Docker-mysql%E4%B8%BB%E4%BB%8E%E9%85%8D%E7%BD%AE/" rel="prev" title="Docker+mysql主从配置">
                  <i class="fa fa-chevron-left"></i> Docker+mysql主从配置
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2019/05/14/Java%E9%9B%86%E5%90%88%E5%AD%A6%E4%B9%A0%E4%B9%8Bfail-fast/" rel="next" title="Java集合学习之fail-fast">
                  Java集合学习之fail-fast <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">一年春又来</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  
<script src="/js/local-search.js"></script>






  





</body>
</html>
